package com.example.testng.utils;

import io.qameta.allure.Allure;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * HTTP请求工具类
 * 封装OkHttp实现HTTP请求的发送
 */


@Component
public class HttpClientUtil {
    private final OkHttpClient client;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType FORM = MediaType.parse("multipart/form-data");
    private ResourceBundle bundle;

    private String baseUrl;

    private String authToken;



    public HttpClientUtil() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    // 读取 application.properties 文件
    public String getProfile(){
        Properties properties = new Properties();
        String activeProfile=null;
        try (InputStream input = new FileInputStream("src/main/resources/application.properties")) {
            properties.load(input);
            activeProfile = properties.getProperty("spring.profiles.active", "default");
        } catch (IOException e) {
            System.err.println("无法读取 application.properties 文件: " + e.getMessage());
            activeProfile = "default"; // 默认配置文件
        }
        return activeProfile;
    }

    /**
     * 添加认证头到请求头Map中
     * @param headers 原始请求头Map
     * @return 添加了认证头的Map
     */
    private Map<String, String> addAuthorizationHeader(Map<String, String> headers) {
        // 添加Cookie头，如果配置了cookie
//        String cookie = bundle.getString("cookie");
//        if (cookie != null && !cookie.isEmpty()) {
//            if (headers == null) {
//                headers = new HashMap<>();
//            }
//            headers.put("Cookie", cookie);
//        }
        // 读取 application.properties 文件
        String activeProfile = getProfile();
        String resourceName = "application" + (activeProfile.isEmpty() ? "" : "-" + activeProfile);
        bundle = ResourceBundle.getBundle(resourceName, Locale.CHINA);
        authToken = bundle.getString("auth-token");
        if (authToken != null && !authToken.isEmpty()) {
            if (headers == null) {
                headers = new HashMap<>();
            }
            headers.put("Authorization",authToken);
            Allure.addAttachment("请求头Authorization",headers.get("Authorization"));
        }
        return headers;
    }

    /**
     * 确保URL是完整的HTTP(S)URL
     * @param url 输入的URL
     * @return 完整的URL
     */
    private String ensureFullUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            throw new IllegalArgumentException("URL不能为空");
        }

        // 如果URL已经是完整的HTTP(S)URL，直接返回
        if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
            return url;
        }
        // 读取 application.properties 文件
        String activeProfile = getProfile();
        String resourceName = "application" + (activeProfile.isEmpty() ? "" : "-" + activeProfile);
        bundle = ResourceBundle.getBundle(resourceName, Locale.CHINA);
        baseUrl = bundle.getString("base-url");
        // 检查baseUrl是否为空
        if (baseUrl == null || baseUrl.trim().isEmpty()) {
            throw new IllegalArgumentException("基础URL未配置，请检查application.properties中的base-url配置");
        }

        // 如果URL以斜杠开头，直接拼接
        if (url.startsWith("/")) {
            return baseUrl + url;
        }

        // 如果URL不以斜杠开头，添加斜杠再拼接
        return baseUrl + "/" + url;
    }

    /**
     * 发送HTTP请求
     *
     * @param url 请求URL
     * @param method HTTP方法 (GET, POST, PUT, DELETE)
     * @param headers 请求头
     * @param requestBody 请求体（JSON格式）
     * @param formData 表单数据（用于文件上传等）
     * @return HTTP响应
     * @throws IOException 如果请求发送失败
     */
    public Response sendRequest(String url, String method, Map<String, String> headers,
                              String requestBody, Map<String, Object> formData) throws IOException {
        // 添加认证头
        headers = addAuthorizationHeader(headers);
        // 确保URL是完整的
        String fullUrl = ensureFullUrl(url);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(fullUrl);

        System.out.println("=================请求头==========================");
        System.out.println(headers);

        // 添加请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置请求方法和请求体
        RequestBody body = null;
        if (formData != null && !formData.isEmpty()) {
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);

            for (Map.Entry<String, Object> entry : formData.entrySet()) {
                if (entry.getValue() instanceof File) {
                    File file = (File) entry.getValue();
                    multipartBuilder.addFormDataPart(entry.getKey(), file.getName(),
                            RequestBody.create(MediaType.parse("application/octet-stream"), file));
                } else if (entry.getValue() instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, String> fileInfo = (Map<String, String>) entry.getValue();
                    File file = new File(fileInfo.get("path"));
                    multipartBuilder.addFormDataPart(entry.getKey(), fileInfo.get("filename"),
                            RequestBody.create(MediaType.parse(fileInfo.get("contentType")), file));
                } else {
                    multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue().toString());
                }
            }
            body = multipartBuilder.build();
        } else if (requestBody != null) {
            body = RequestBody.create(JSON, requestBody);
        }

        switch (method.toUpperCase()) {
            case "GET":
                requestBuilder.get();
                break;
            case "POST":
                requestBuilder.post(body != null ? body : RequestBody.create(JSON, ""));
                break;
            case "PUT":
                requestBuilder.put(body != null ? body : RequestBody.create(JSON, ""));
                break;
            case "DELETE":
                if (body != null) {
                    requestBuilder.delete(body);
                } else {
                    requestBuilder.delete();
                }
                break;
            default:
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }

        // 发送请求
        Request request = requestBuilder.build();
        System.out.println("发送请求到: " + fullUrl);
        System.out.println("请求方法: " + method);
        if (requestBody != null) {
            System.out.println("请求体: " + requestBody);
        }

        try {
            Response response = client.newCall(request).execute();
            System.out.println("收到响应: " + response.code());
            return response;
        } catch (IOException e) {
            System.err.println("请求失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 发送GET请求
     */
    public Response get(String url, Map<String, String> headers) throws IOException {
        return sendRequest(url, "GET", headers, null, null);
    }

    /**
     * 发送POST请求
     */
    public Response post(String url, Map<String, String> headers, String requestBody,
                        Map<String, Object> formData) throws IOException {
        return sendRequest(url, "POST", headers, requestBody, formData);
    }

    /**
     * 发送PUT请求
     */
    public Response put(String url, Map<String, String> headers, String requestBody,
                       Map<String, Object> formData) throws IOException {
        return sendRequest(url, "PUT", headers, requestBody, formData);
    }

    /**
     * 发送DELETE请求
     */
    public Response delete(String url, Map<String, String> headers, String requestBody,
                         Map<String, Object> formData) throws IOException {
        return sendRequest(url, "DELETE", headers, requestBody, formData);
    }
}